#include "hardware.h"
#include <delays.h>
#include "p18cxxx.h"
#include "dht11.h"
#include "mydelay.h"

#ifndef DHT_C
#define DHT_C

extern unsigned long msec;

/*
extern unsigned char TOUT;

void StartSignal(){
  TRIS_DHT = 0;     // Data port is output
  DHT    = 0;
  Delay_ms(25);
  DHT    = 1;
  Delay_us(30);
  TRIS_DHT = 1;     // Data port is input
}

unsigned short CheckResponse(){
  TOUT = 0;
  TMR2 = 0;
  T2CONbits.TMR2ON = 1;      // start timer
  while(!DHT && !TOUT);
  if (TOUT) return 0;
  else {
   TMR2 = 0;
   while(DHT && !TOUT);
   if (TOUT) return 0;
   else {
    T2CONbits.TMR2ON = 0;
    return 1;
   }
  }
}

unsigned short ReadByte(){
  unsigned short num = 0, t;
  unsigned char i;
  TRIS_DHT = 1;
  for (i=0; i<8; i++){
   while(!DHT);
   TMR2 = 0;
   T2CONbits.TMR2ON = 1;
   while(DHT);
   T2CONbits.TMR2ON = 0;
   if(TMR2 > 40) num |= 1<<(7-i);  // If time > 40us, Data is 1
  }
  return num;
}
*/

void DHTStartSignal(){
  TRIS_DHT = 0;     // Data port is output
  DHT    = 0;
  Delay_ms(30);    // Low for at 30ms
  DHT    = 1;
  TRIS_DHT = 1;     // Data port is input
  //Delay10TCYx (36);    // High for 30 us
}

unsigned char DHTCheckResponse(){
  unsigned long t=msec;

  //Delay10TCYx (1);

  t=msec;
  while(DHT && (msec-t<100)) ;

  //Delay10TCYx (36);
  
  // if(DHT) return 1;

  t=msec;
  while((!DHT) && (msec-t<100)) ;

  //Delay10TCYx (36);
  // if(!DHT) return 2;

  t=msec;
  while(DHT && (msec-t<100));
  return 0;
}

unsigned char ReadDHT(){
  unsigned long t=msec;
  unsigned char num = 0;
  unsigned char i;
  //TRIS_DHT = 1;
  for (i=0; i<8; i++){
     t=msec;
     while((!DHT) && (msec-t<100)) ;
     
     Delay10TCYx (40);
     //Delay_us(10);
     if(DHT) num |= 1<<(7-i);

     t=msec;
     while(DHT && (msec-t<100)) ;
  }
  return num;
}

#endif
